<template>
	<view class="login_box">
		<view class="text_login">
			<!-- logo -->
			<image class="login_logo" src="../../static/logo/orange.png" alt="" />

			<!-- 表单区域 -->
			<view class="login_phone">
				<text>手机号</text>
				<input type="text" maxlength="11" v-model="userPhone" />
			</view>
			<view class="login_code">
				<text>验证码</text>
				<input type="text" maxlength="4" v-model="userCode" />
				<view hover-class="touchOpacity" @click="sendCode">{{ code }}</view>
			</view>

			<!-- 登录按钮 -->
			<view class="login_but" hover-class="touchOpacity" @click="login"><text space="ensp">登 录</text></view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			userPhone: '',
			userCode: '',
			code: '发送验证码',
			sendmsm: true //允许发送验证码
		};
	},
	methods: {
		sendCode() {
			if (this.sendmsm) {
				// 1.校验数据格式 test:bool
				if (!/^1[3456789]\d{9}/.test(this.userPhone)) {
					this.$tip.tip('手机号格式有误!');
					return false;
				}
				this.$http({
					url: 'sms',
					data: { phone: this.userPhone }
				}).then(res => {
					// console.log(res.list.code);
					//将验证码和 当前时间戳 放入本地存储
					uni.setStorageSync('msm', { msm: res.list.code, time: +new Date() });
					this.sendmsm = false; //此时已经请求过了，不允许再次发送验证码
					let time = 10;
					this.timer = setInterval(() => {
						time--;
						this.code = time + 's';
						if (time < 1) {
							clearInterval(this.timer);
							this.code = '发送验证码';
							let time = 10;
							this.sendmsm = true;
						}
					}, 1000);
				});
			} else {
				this.$tip.tip('请稍后再试！');
			}
		},
		login() {
			//1.点击登录时 将本地存储中的数据取出来
			let { msm, time } = uni.getStorageSync('msm');
			// console.log(msm, time);
			// console.log(this.userPhone, this.userCode);
			//2.做判断
			if (this.userCode != msm || this.userCode == '') {
				this.$tip.tip('验证码输入不正确！');
				return false;
			}
			//当前时间戳-发送验证码时的时间戳 大于5分钟就显示验证码过期
			if (+new Date() - time > 300000) {
				this.$tip.tip('验证码已过期！');
				uni.removeStorageSync('msm');
				return false;
			}
			if (!/^1[3456789]\d{9}/.test(this.userPhone)) {
				this.$tip.tip('手机号格式有误!');
				return false;
			}
			// 3.提交登录
			this.$http({
				url: 'smslogin',
				method: 'post',
				data: {
					phone: this.userPhone
				}
			}).then(res => {
				if (res.code == 200) {
					this.$tip.tip(res.msg + '！即将跳转到首页');
					uni.setStorageSync('userInfo', res.list);
					uni.setStorageSync('token', res.list.token);
					uni.removeStorageSync('msm');
					setTimeout(() => {
						uni.switchTab({
							url: '../index/index'
						});
					}, 1000);
				}
				console.log(res);
			});
		}
	}
};
</script>

<style>
/* 引入样式 */
@import url('@/static/css/textlogin.css');
</style>
